package com.ayic.garbagerecycle.mapper;

import com.ayic.garbagerecycle.pojo.User;
import com.ayic.garbagerecycle.pojo.WasteRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper {
    /**
     * 根据用户名查询用户信息
     * @param username 用户名
     * @return 用户对象，如果不存在则返回null
     */
    @Select("SELECT user_id AS userId, username, password, email, role, created_at AS createdAt FROM users WHERE username = #{username}")
    User selectUserByName(String username);

    /**
     * 更新用户密码
     * @param username 用户名
     * @param newPassword 新密码
     * @return 更新成功返回1，否则返回0
     */
    @Update("UPDATE users SET password = #{newPassword} WHERE username = #{username}")
    int updatePassword(String username, String newPassword);

    /**
     * 更新用户邮箱
     * @param username 用户名
     * @param newEmail 新邮箱
     * @return 更新成功返回1，否则返回0
     */
    @Update("UPDATE users SET email = #{newEmail} WHERE username = #{username}")
    int updateEmail(String username, String newEmail);

    /**
     * 统计用户投放垃圾种类及次数
     * @param userId 用户ID
     * @return Map<垃圾种类名称, 投放次数>
     */
    @Select("SELECT wt.waste_type_name, COUNT(*) AS count FROM waste_records wr " +
            "JOIN waste_types wt ON wr.waste_type_id = wt.waste_type_id " +
            "WHERE wr.user_id = #{userId} GROUP BY wt.waste_type_name")
    List<Map<String, Object>> countWasteTypesByUserId(int userId);

    /**
     * 查询用户的所有回收记录
     * @param userId 用户ID
     * @return 回收记录列表
     */
    @Select("SELECT record_id AS recordId, station_id AS stationId, waste_type_id AS wasteType, weight, volume, value, created_at AS createdAt,user_id AS userId " +
            "FROM waste_records WHERE user_id = #{userId} ORDER BY created_at DESC")
    List<WasteRecord> selectWasteRecordsByUserId(int userId);

    @Select("SELECT user_id AS userId FROM users WHERE username = #{username}")
    Integer getUserIdByUsername(String username);
}
